package com.quectel.cms.controller.grid;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.grid.dto.*;
import com.quectel.core.module.grid.service.GridMemberGridBindingService;
import com.quectel.core.module.grid.service.GridMemberService;
import com.quectel.core.module.grid.service.GridPlanGridBindingService;
import com.quectel.core.module.grid.service.GridPlanService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/02/03 15:45
 */
@RestController
@RequestMapping("gridPlan")
@Tag(name = "GridPlanController", description = "网格巡检计划相关api")
public class GridPlanController extends BaseController {

    @DubboReference
    private GridPlanService gridPlanService;
    @DubboReference
    private GridMemberGridBindingService gridMemberGridBindingService;
    @DubboReference
    private GridMemberService gridMemberService;
    @DubboReference
    private GridPlanGridBindingService gridPlanGridBindingService;

    /**
     * 选择多个网格，对网格绑定的网格员去重
     *
     * @param ids
     * @return
     */
    @PostMapping("queryGridMembers")
    @Operation(summary = "根据条件搜索网格员列表")
    public Response<List<GridMemberDto>> queryGridMembers(@RequestBody Long[] ids) {

        List<GridMemberDto> result = new ArrayList<>();
        if (ids.length == 0) {
            return Response.<List<GridMemberDto>>ok().wrap(result);
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put(GridConstant.GRID_IDS, Arrays.asList(ids));
        List<GridMemberGridBindingDto> gridMemberGridBindingDtos = gridMemberGridBindingService.queryList(queryMap);

        Set<Long> myset = new HashSet<>();
        for (GridMemberGridBindingDto bind : gridMemberGridBindingDtos) {
            myset.add(bind.getGridMemberId());
        }
        List<Long> gridMemberIds = new ArrayList(myset);

        for (int i = 0; i < gridMemberIds.size(); i++) {
            Long memberId = gridMemberIds.get(i);
            GridMemberDto gridMemberDto = gridMemberService.selectCacheById(memberId);
            if (gridMemberDto != null) {
                result.add(gridMemberDto);
            }
        }

        return Response.<List<GridMemberDto>>ok().wrap(result);
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "gridPlan:list")
    @Operation(summary = "网格巡检计划的分页查询列表")
    public Response<Page<GridPlanDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = gridPlanService.queryTotal(request.getParams());

        List<GridPlanDto> list = null;
        if (total > 0) {
            list = gridPlanService.queryList(request.getParams());
            // 计划查网格
            for (GridPlanDto plan : list) {
                List<Long> bindGrid = plan.getGridList().stream().map(GridDto::getId).collect(Collectors.toList());
                StringBuilder builder = new StringBuilder();
                Set<Long> recordSet = new HashSet<>();
                for (Long gridId : bindGrid) {
                    Map<String, Object> sqlMap = new HashMap<>();
                    sqlMap.put(LambdaUtil.getFieldName(GridMemberGridBindingDto::getGridId), gridId);
                    List<Long> newList = gridMemberGridBindingService.queryList(sqlMap)
                            .stream().map(GridMemberGridBindingDto::getGridMemberId).collect(Collectors.toList());
                    for (Long memeberId : newList) {
                        recordSet.add(memeberId);
                    }
                }
                List<Long> memberIds = new ArrayList(recordSet);

                // 人名填充
                for (Long memberId : memberIds) {
                    GridMemberDto gridMemberDto = gridMemberService.selectCacheById(memberId);
                    if (gridMemberDto != null) {
                        builder.append(gridMemberDto.getName()).append("; ");
                    }
                }
                plan.setMemberNameStr(builder.toString());
            }

            // 网格查网格员

        } else {
            list = new ArrayList<>();
        }

        Page<GridPlanDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridPlanDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "gridPlan:edit")
    @Operation(summary = "查询单条网格巡检计划记录")
    public Response<GridPlanDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridPlanService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridPlanDto gridPlanDto = gridPlanService.selectById(id);

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put(LambdaUtil.getFieldName(GridPlanGridBindingDto::getPlanId), id);
        List<GridPlanGridBindingDto> gridPlanGridBindingDtos = gridPlanGridBindingService.queryList(queryMap);
        List<Long> bindGrid = gridPlanGridBindingDtos.stream()
                .map(GridPlanGridBindingDto::getGridId).collect(Collectors.toList());
        gridPlanDto.setBindGrid(bindGrid);

        return Response.<GridPlanDto>ok().wrap(gridPlanDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "gridPlan:info")
    @Operation(summary = "查询单条网格巡检计划记录")
    public Response<GridPlanDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridPlanService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridPlanDto gridPlanDto = gridPlanService.selectById(id);

        return Response.<GridPlanDto>ok().wrap(gridPlanDto);
    }

    /**
     * 保存
     *
     * @param gridPlanDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "gridPlan:edit")
    @Operation(summary = "保存单条网格巡检计划记录")
    public Response<Object> save(@RequestBody @Validated GridPlanDto gridPlanDto) {

        //填充基础数据
        fillSaveCommonData(gridPlanDto);

        // 计划必须选择网格
        if (CollectionUtils.isEmpty(gridPlanDto.getBindGrid())) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        gridPlanService.save(gridPlanDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param gridPlanDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "gridPlan:edit")
    @Operation(summary = "修改单条网格巡检计划记录")
    public Response<Object> update(@RequestBody @Validated GridPlanDto gridPlanDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(gridPlanDto.getId()));
        if (gridPlanService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(gridPlanDto);

        if (CollectionUtils.isEmpty(gridPlanDto.getBindGrid())) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        gridPlanService.saveOrUpdate(gridPlanDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "gridPlan:delete")
    @Operation(summary = "批量删除存在的网格巡检计划记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (gridPlanService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        gridPlanService.deleteBatch(ids);

        return Response.ok();
    }
}
